import Vue from 'vue'
import VueRouter from 'vue-router'

//导入组件对象
import Dashboard from '../views/Dashboard'
import Category from '../views/Category'
import Article from '../views/Article'
import Login from '../components/Login'
import Home from '../views/Home'
import ArticleAdd from '../views/ArticleAdd'

Vue.use(VueRouter)

const routes = [
  //匹配路由规则,加载对应的组件
  { path: '/login', name: 'Login', component: Login },
  {
    path: '/home',
    component: Home,
    meta: { needLogin: true },
    children: [
      {
        path: '/home/dashboard',
        component: Dashboard,
        meta: {
          needLogin: true, //校验判断
        },
      },

      { path: '/home/category', component: Category },
      { path: '/home/article', component: Article },
      { path: '/home/article/add', component: ArticleAdd },
    ],
  },
  //由于是从上到下匹配的,最后可以写*代表所有路由,其实就是除以上剩下的路由
  { path: '*', component: Login },
  //{ path: '*', redirect: '/' },另一种写法
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})
// router.beforeEach((to, from, next) => {
//   let token = localStorage.getItem('token')
//   if (token || to.path === '/login') {
//     next()
//   } else {
//     //next传递一个路由对象作为参数,跳转到新页面
//     next('/login')
//   }
// })
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  if (!token && to.name !== 'Login') {
    next({ name: 'Login' })
  }
  //next传递一个路由对象作为参数,跳转到新页面
  else next()
})
// router.afterEach((to, from, next) => {
//   if (to.name === 'Home') {
//     alert('确定进入吗')
//   }
// })
export default router
